function addTr8nCSS(doc, src) {
  var css = doc.createElement('link');
  css.setAttribute('type', 'text/css');
  if (src.indexOf('//') != -1) {
    css.setAttribute('href', src);
  } else {
    css.setAttribute('href', '<%=uri.scheme%>://<%=uri.host%><%=":#{uri.port}" unless uri.port==80 %>' + src);
  }
  css.setAttribute('rel', 'stylesheet');
  css.setAttribute('media', 'screen');
  doc.getElementsByTagName('head')[0].appendChild(css);
  return css;
}
 
function addTr8nScript(doc, id, src, onload) {
  var script = doc.createElement('script');
  script.setAttribute('id', id);
  script.setAttribute('type', 'application/javascript');
  if (src.indexOf('//') != -1) {
    script.setAttribute('src', src);  
  } else {
    script.setAttribute('src', '<%=uri.scheme%>://<%=uri.host%><%=":#{uri.port}" unless uri.port==80 %>' + src);  
  }
  script.setAttribute('charset', 'UTF-8');
  if (onload) script.onload = onload;
  doc.getElementsByTagName('head')[0].appendChild(script);
  return script;
}

<% params[:debug] = true %>

(function(window) {
  <% if params[:immediate] == 'true' %>   
    initTr8n();
  <% else %>
    if (window.addEventListener) window.addEventListener('load', initTr8n, false); // Standard
    else if (window.attachEvent) window.attachEvent('onload', initTr8n); // Microsoft
    window.setTimeout(function(){
      initTr8n();
    }, 1000);  
  <% end %>

  <% if Tr8n::Config.enable_software_keyboard? %>
    VKI_default_layout = "<%=Tr8n::KeyboardMapping.current_1_49%>";
  <% end %>  

  function initTr8n() {
    if (window.tr8n_enabled) return;
    window.tr8n_enabled = true;

    addTr8nCSS(window.document, '/assets/tr8n/tr8n.css');
    <% if Tr8n::Config.enable_software_keyboard? %>
      addTr8nCSS(window.document, '/assets/tr8n/keyboard_1_49.css');
    <% end %>  

    addTr8nScript(window.document, 'tr8n-jssdk', "<%= params[:debug] ? '/assets/tr8n/tr8n.debug.js': '/assets/tr8n/tr8n.js' %>", function() {
      addTr8nScript(window.document, 'tr8n-proxy', "/tr8n/api/proxy/init.js?<%=params.slice(:debug, :tml, :text, :source, :page_locale).merge(:t => Time.now.to_i).to_query.html_safe%>", function() {
        if (typeof(onTr8nReady) === 'function') {
           onTr8nReady();
        }
      });
    });
  }
})(window);
